﻿using HCMS.CommonDtos;
using HCMS.Entities.Base;
using HCMS.Extensions;
using HCMS.IServices.Base;
using Microsoft.AspNetCore.Mvc;

namespace HCMS.Web.Manage.Controllers.Module.Base
{
    /// <summary>
    /// 敏感词
    /// </summary>
    public class SensitiveWordsController : ModuleController
    {
        private readonly ISensitiveWordsAppService sensitiveWordsAppService;

        public SensitiveWordsController(
            ISensitiveWordsAppService sensitiveWordsAppService
         )
        {
            this.sensitiveWordsAppService = sensitiveWordsAppService;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return View($"{BasePath}/Base/SensitiveWords/List.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <returns></returns>
        [ActionName("List")]
        [HttpPost]
        public async Task<IActionResult> PostList()
        {
            var searchArgs = new SearchArgsDto()
            {
                Status = Request.Form["status"].ToInt(9999),

                SearchName = Request.Form["searchName"].ToString(""),
                SearchKey = Request.Form["searchKey"].ToString(""),

                ClassId = Request.Form["classId"].ToInt(0)
            };

            var pager = new PagerArgsDto()
            {
                CurrentPageIndex = Request.Form["page"].ToInt(1),
                PageSize = Request.Form["limit"].ToInt(10)
            };

            var result = await sensitiveWordsAppService.ManageList(searchArgs, pager);

            return Json(new { code = 0, data = result.Data, count = result.PagerInfo.RowCount, msg = "ok" });
        }
        #endregion

        #region 新增、编辑、保存
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            var model = new SensitiveWords();
            return View($"{BasePath}/Base/SensitiveWords/Edit.cshtml", model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(int id)
        {
            if (id <= 0)
            {
                return Content("参数无效");
            }

            var model = await sensitiveWordsAppService.BaseFirstOrDefaultAsync(t => t.Id == id);
            if (model == null)
            {
                return Content($"没有找到【id：{id}】敏感词信息");
            }

            return View($"{BasePath}/Base/SensitiveWords/Edit.cshtml", model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sensitiveWords"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save(SensitiveWords sensitiveWords)
        {
            SensitiveWords? result = null;

            if (sensitiveWords == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数错误" });
            }

            if (string.IsNullOrWhiteSpace(sensitiveWords.Title))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写敏感词" });
            }
            var hasRepeat = await sensitiveWordsAppService.HasRepeat(sensitiveWords.Id, sensitiveWords.Title);
            if (hasRepeat)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = string.Format("已经有同名的敏感词【{0}】，不需要重复添加", sensitiveWords.Title) });
            }

            if (sensitiveWords.ClassId <= 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请选择分类" });
            }

            var entity = await sensitiveWordsAppService.BaseFirstOrDefaultAsync(t => t.Id == sensitiveWords.Id);
            if (entity != null)
            {
                await TryUpdateModelAsync(entity);
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;

                result = await sensitiveWordsAppService.BaseUpdateAsync(entity);
            }
            else
            {
                entity = new SensitiveWords()
                {
                    CreateTime = DateTime.Now,
                    CreateUser = CurrentAdmin.AdminName,
                    UpdateTime = DateTime.Now,
                    UpdateUser = CurrentAdmin.AdminName,
                };
                await TryUpdateModelAsync(entity);

                result = await sensitiveWordsAppService.BaseInsertAsync(entity);
            }

            if (result != null)
            {
                // 刷新 Redis 缓存
                await sensitiveWordsAppService.AllList(true);

                return Json(new AjaxResultDto() { Message = "处理成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "处理失败" });
            }
        }
        #endregion
    }
}
